package com.example.smartgreenhouse.service.impl;

import com.example.smartgreenhouse.entity.LightOperationLog;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.mapper.LightOperationLogMapper;
import com.example.smartgreenhouse.mqtt.MqttMessageSender;
import com.example.smartgreenhouse.service.LightService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class LightServiceImpl implements LightService {

    private final LightOperationLogMapper lightOperationLogMapper;
    private final MqttMessageSender mqttMessageSender;

    @Value("${mqtt.topic.light_cmd}")
    private String topicLightCmd;

    @Value("${mqtt.topic.light_auto_cmd}")
    private String topicLightAutoCmd;


    @Override
    @Transactional
    public Map<String, Object> setLightAuto(Long lightId, Long greenhouseId,
                                            Long operatorId, Integer action) {
        try {
            mqttMessageSender.publish(topicLightAutoCmd, String.valueOf(action));
            log.info("灯光自动控制指令发送成功：lightId={}, action={}", lightId, action);
        } catch (Exception e) {
            log.error("MQTT指令发送失败：{}", e.getMessage());
            throw new BusinessException("灯光自动控制指令发送失败");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("status", "success");
        result.put("message", action == 1 ? "灯光自动控制开启" : "灯光自动控制关闭");
        result.put("operationTime",LocalDateTime.now());
        return result;
    }

    @Override
    @Transactional
    public LightOperationLog controlLight(Long lightId, Long greenhouseId, String isOn,
                                         Long operatorId) {
        // 校验ENUM值
        if (!Arrays.asList("0", "1").contains(isOn)) {
            throw new BusinessException("灯光状态必须是'0','1'");
        }

        // 发送控制指令

        try {
            mqttMessageSender.publish(topicLightCmd, String.valueOf(isOn));
            log.info("灯光控制指令发送成功：lightId={}, isOn={}", lightId, isOn);
        } catch (Exception e) {
            log.error("MQTT指令发送失败：{}", e.getMessage());
            throw new BusinessException("灯光控制指令发送失败");
        }


        // 记录操作日志
        LightOperationLog log = new LightOperationLog();
        log.setLightId(lightId);
        log.setGreenhouseId(greenhouseId);
        log.setIsOn(isOn);
        log.setOperatorId(operatorId);
        log.setOperateTime(LocalDateTime.now());
        lightOperationLogMapper.insert(log);
        return log;
    }

    @Override
    public List<LightOperationLog> getLightHistory(Long lightId) {
        return lightOperationLogMapper.selectByLightId(lightId);
    }

}